import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:flutter/material.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";

class PasswordTextField extends StatefulWidget {
  final String name;
  final InputDecoration decoration;
  final String? Function(String?)? validator;

  const PasswordTextField({
    super.key,
    required this.name,
    this.decoration = const InputDecoration(),
    this.validator,
  });

  @override
  State<PasswordTextField> createState() => _PasswordTextFieldState();
}

class _PasswordTextFieldState extends State<PasswordTextField> {
  final GlobalKey<FormBuilderFieldState> textFieldKey =
      GlobalKey<FormBuilderFieldState>();
  final FocusNode focusNode = FocusNode();
  bool _showEyes = false;
  bool _obscureText = true;

  @override
  void initState() {
    super.initState();
    focusNode.addListener(() => setState(() => _showEyes = focusNode.hasFocus));
  }

  @override
  void dispose() {
    super.dispose();
    focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget? suffixIcon;
    if (_showEyes || textFieldKey.currentState?.value?.isNotEmpty == true) {
      suffixIcon = GestureDetector(
        onTap: () => setState(() => _obscureText = !_obscureText),
        child: Padding(
          padding: const EdgeInsets.only(right: 10),
          child: Icon(
            _obscureText
                ? Icons.visibility_off_rounded
                : Icons.visibility_rounded,
            color: ThemeVars.colorTextTer,
          ),
        ),
      );
    }
    return FormBuilderTextField(
      key: textFieldKey,
      decoration: widget.decoration.copyWith(suffixIcon: suffixIcon),
      focusNode: focusNode,
      name: widget.name,
      obscureText: _obscureText,
      validator: widget.validator,
    );
  }
}
